# -*- encoding: utf-8 -*-
"""
    读取对比数据/可视化
    load_excel_vis
"""

from openpyxl import load_workbook as pyxl_load_workbook
import numpy as np

from utils.numeric import grid_interp
from utils.constant import InterpMode

def load_olga_groundtruth_result_se(params, gt_path):
    # se 等同于visual_olga_time_se(临时代码，后续待修改)

    # 0. 获取计算值的时间
    timepoint = params["record_time"] #params["record_time"]

    # openpyxl
    all_data, sheet_names = csv_pyxl_loader(gt_path)

    # 获取所有数据
    gt = all_data['随时间变化']

    # 获得计算到的时间点最近的对比数据
    alltimepoints = np.asarray(gt['X'], dtype=np.float64)

    idx = np.argmin(np.abs(alltimepoints - timepoint))

    # 获取对比数据
    gt_alpha_L = get_data_by_keys(gt, idx, param='Holdup')
    gt_p = get_data_by_keys(gt, idx, param='pressure')
    gt_flow_g = get_data_by_keys(gt, idx, param='g_volume_flow')*3600*24
    gt_flow_L = get_data_by_keys(gt, idx, param='L_volume_flow')*3600*24
    gt_T = get_data_by_keys(gt, idx, param='T')

    gt_flow_L = gt_flow_L[:-1]
    gt_flow_g = gt_flow_g[:-1]

    # 2. 计算值
    flow_g = np.zeros_like(gt_flow_g)
    flow_L = np.zeros_like(gt_flow_L)
    p = np.zeros_like(gt_p)
    T = np.zeros_like(gt_T)
    alpha_L = np.zeros_like(gt_alpha_L)

    # 气体体积流量 =速度*截面积*截面分数
    # 液体体积流量 =速度*截面积*截面分数
    # 压力
    # 温度
    # 持液率
    area = params['cross_section_area_segment']
    flow_g[:] = params['V_g_segment'][:] * grid_interp(params['alpha_g_node'], InterpMode.MID)[:] * area*3600*24
    flow_L[:] = params['V_L_segment'][:] * grid_interp(params['alpha_L_node'], InterpMode.MID)[:] * area*3600*24
    p[:] = grid_interp(params['p_node'], InterpMode.MID)[:]
    T[:] = grid_interp(params['T_node'], InterpMode.MID)[:]
    alpha_L[:] = grid_interp(params['alpha_L_node'], InterpMode.MID)[:]

    # # 单位转换
    # gt_flow_g = gt_flow_g / 86400 # /d 到 /s
    # gt_flow_L = gt_flow_L / 86400 # /d 到 /s
    # gt_p[:] = gt_p * 1e5  # bar转换为帕
    # gt_T[:] = gt_T[:] + 273.15  # 转换为开

    # 忽略入口
    gt_flow_g = gt_flow_g[1:]
    flow_g = flow_g[1:]
    gt_flow_L = gt_flow_L[1:]
    flow_L = flow_L[1:]
    gt_p = gt_p[1:]
    p = p[1:]
    gt_T = gt_T[1:]
    T = T[1:]
    gt_alpha_L = gt_alpha_L[1:]
    alpha_L = alpha_L[1:]

    return gt_flow_g, gt_flow_L, gt_p, gt_T, gt_alpha_L, flow_g, flow_L, p, T, alpha_L


def get_data_by_keys(gt, idx, param = 'Holdup'):
    """
    :param gt: panda DataFrame，读取的olga对比结果
    :param idx: int, 时间点
    :param param: dict: 参数字典
    :return: data, numpy.ndarray， 获取的数据
    """
    keys = []
    if param == 'Holdup':
        keywords = "Holdup (liquid volume fraction including solids)"
    elif param == 'pressure':
        keywords = "Pressure"
    elif param == 'g_volume_flow':
        keywords = "Gas volume flow"
    elif param == 'L_volume_flow':
        keywords = "Total liquid volume flow"
    elif param == 'T':
        keywords = "Fluid temperature"

    for k in gt.keys():
        if keywords in k:
            keys.append(k)
    # 检查字符串意义顺序和索引顺序是否一致，否则排序
    check_sort_in_keys(keys)
    # 生成数组
    lens = len(keys)
    data = np.zeros(lens)
    for i in range(0,lens):
        data[i] = gt[keys[i]][idx]
    return data

def check_sort_in_keys(keys):
    # 检查字符串意义顺序和索引顺序是否一致，否则排序
    trimmed_data = trim_common_parts(keys)
    trimmed_data = np.array(trimmed_data, dtype=int)
    sorted_indices = None
    if not np.array_equal(trimmed_data,np.sort(trimmed_data)):
        sorted_indices = np.argsort(trimmed_data)
        keys =  [keys[i] for i in sorted_indices]

def trim_common_parts(strings):
    # 1. 从前向后去除相同字符
    min_length = min(len(s) for s in strings)
    start_index = 0
    for i in range(min_length):
        if len(set(s[i] for s in strings)) > 1:
            start_index = i
            break

    # 2. 从后向前去除相同字符
    end_index = 0
    for i in range(1, min_length - start_index + 1):
        if len(set(s[-i] for s in strings)) > 1:
            end_index = -i + 1  # 计算最终的结束索引
            break

    # 3. 截取中间不同的部分
    trimmed = [s[start_index:end_index if end_index != 0 else None] for s in strings]
    return trimmed

def csv_pyxl_loader(gt_path):
    """
    使用 openpyxl 读取多工作表的csv文件
    Args:
        gt_path: str,工作表地址
    Returns:
        all_data：dict, 字典形式的数据
        sheet_names, list str, 工作表sheet名字
    """
    # openpyxl
    workbook = pyxl_load_workbook(gt_path, read_only=True)
    sheet_names = workbook.sheetnames
    all_data = {}
    for sheet in sheet_names:
        # data = pd.read_excel(gt_path, sheet_name=sheet)
        worksheet = workbook[sheet]
        data = []
        for row in worksheet.iter_rows(values_only=True):
            data.append(row)
        keys = data[0]
        values = np.asarray(data[1:])
        data_dict = {}
        for i in range(0, len(keys)):
            data_dict[keys[i]] = values[:, i]
        all_data[sheet] = data_dict
    return all_data, sheet_names